package com.example.music.controller;

import com.alibaba.druid.sql.visitor.functions.If;
import com.example.music.entity.Collect;
import com.example.music.service.CollectService;
import com.example.music.utils.AjaxJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("collect")
public class CollectController {
    @Autowired
    CollectService collectService;

    @PostMapping("add")
    public AjaxJson add(@RequestBody Collect collect){
        List<Collect> collects = collectService.selectAll();
        boolean b = collects.parallelStream().anyMatch(e -> {
            if (collect.getType() == 0) {
                if (e.getSongId().equals(collect.getSongId()))
                    return true;
            } else {
                if (e.getSongListId().equals(collect.getSongListId()))
                    return true;
            }
            return false;
        });
        if (b){
            del(collect);
            return AjaxJson.get(201,"已添加过");
        }
        Integer add = collectService.add(collect);
        return AjaxJson.getSuccess(add.toString());
    }

    @PostMapping("delete")
    public AjaxJson delete(@RequestBody Collect collect){
        HashMap<String, Object> map = new HashMap<>();
        map.put("user_id",collect.getUserId());
        if (collect.getType()==0){
            map.put("song_id",collect.getSongId());
        }else {
            map.put("song_list_id",collect.getSongListId());
        }
        collectService.deleteByParams(map);
        return AjaxJson.getSuccess();
    }

    @GetMapping("searchByUserId")
    public AjaxJson searchByUserId(@RequestParam String id){
        List<Collect> user_id = collectService.selectItemsByParam("user_id", id);
        return AjaxJson.getSuccessData(user_id);
    }

    public void del(Collect collect){
        HashMap<String, Object> map = new HashMap<>();
        map.put("user_id",collect.getUserId());
        if (collect.getType()==0){
            map.put("song_id",collect.getSongId());
        }else {
            map.put("song_list_id",collect.getSongListId());
        }
        collectService.deleteByParams(map);
    }

}
